﻿using System;
using RayDen.Library.Core;
using RayDen.Library.Core.Primitives;
using RayDen.Library.Data.Imaging;

namespace RayDen.RayEngine.Data
{
    public class LightUtils
    {
        public static double PerezBase(double[] lam, double theta, double gamma)
        {
            return (1.0 + lam[1] * Math.Exp(lam[2] / Math.Cos(theta))) *
                   (1.0 + lam[3] * Math.Exp(lam[4] * gamma) + lam[5] * Math.Cos(gamma) * Math.Cos(gamma));
        }

        public static float RiAngleBetween(float thetav, float phiv, float theta, float phi)
        {
            float cospsi = MathLab.Sin(thetav) * MathLab.Sin(theta) * MathLab.Cos(phi - phiv) + MathLab.Cos(thetav) * MathLab.Cos(theta);
            if (cospsi >= 1f)
                return 0f;
            if (cospsi <= -1f)
                return MathLab.M_PI;
            return (float)Math.Acos(cospsi);
        }

        public static void ChromaticityToSpectrum(float Y, float x, float y, out RgbSpectrum s)
        {
            float X, Z;


            if (!y.NearEqual(0f))
                X = (x / y) * Y;
            else
                X = 0f;

            if (!y.NearEqual(0f)  && !Y.NearEqual(0f))
                Z = (1f - x - y) / y * Y;
            else
                Z = 0f;

            // Assuming sRGB (D65 illuminant)
            s.c1 = 3.2410f * X - 1.5374f * Y - 0.4986f * Z;
            s.c2 = -0.9692f * X + 1.8760f * Y + 0.0416f * Z;
            s.c3 = 0.0556f * X - 0.2040f * Y + 1.0570f * Z;
        }

        public static void ChromaticityToSpectrum(float Y, float x, float y, out SampledSpectrum s)
        {
            float X, Z;

            Y = Math.Abs(Y);

            if (!y.NearEqual(0f))
                X = (x / y) * Y;
            else
                X = 0f;

            if (!y.NearEqual(0f) && !Y.NearEqual(0f))
                Z = (1f - x - y) / y * Y;
            else
                Z = 0f;

            var lum = RgbSpectrum.FromXYZ(new[] { X, Y, Z });

            s = ColorFactory.FromRgb(ref lum, SpectrumType.Illuminant);
            
        }
    }
}